
# Load Libraries
library(tidyr)
library(dplyr)
library(ggplot2)
library(scales)
library(ggsignif)
library(hrbrthemes)
library(extrafont)
library(ggthemes)
library(grid)

loadfonts()


# read survey responses responses
mydata.img <- read.csv(file = "data/study_1/responses_per_image.csv", head = T, sep = c(","))

# Read features df
features <- read.csv(file = "data/features_labels_wide.csv", head = T, sep = c(","))
truth <- features[, c("file_id", "escaped")]
truth$file_id <- as.character(truth$file_id)

# merge
mydata.img.truth <-
  merge(mydata.img,
        truth,
        by.x = c("Img"),
        by.y = c("file_id"))

# Calculate accuracy manually
mydata.img.truth$Guessed_Right <- as.numeric(mydata.img.truth$Esc == mydata.img.truth$escaped)

# Aggregate per user
mydata.analysis <- mydata.img.truth %>% group_by(Condition, TurkerID) %>% summarise(c = length(Guessed_Right), m = mean(Guessed_Right))
mean(mydata.analysis[which(mydata.analysis$Condition == "control"), ]$m)
mean(mydata.analysis[which(mydata.analysis$Condition == "training"), ]$m)

lm.DiM <- lm(m ~ Condition, data = mydata.analysis)
summary(lm.DiM)

mydata.analysis <- mydata.img.truth %>%
  group_by(Condition, TurkerID) %>%
  summarise(c = length(Guessed_Right),
            m = mean(Guessed_Right))

#
# STUDY 1 FIGURE
#
plotdata <- mydata.analysis %>% group_by(Condition) %>% summarise(mm = mean(m), se = sciplot::se(m))
plotdata$Condition <- c("No training", "Training")

pdf(file="plots/pdfs/study_1_acc.pdf", width = 8, height = 8)

plt <- plotdata %>%
  ggplot(aes(x=Condition,y=mm,fill=Condition), color=Condition) +  
  stat_summary(fun.y=mean,position=position_dodge(),geom="bar",width=0.6)+
  geom_text(aes(label=round(mm,2)),size = 9, position = position_stack(vjust = 0.85),color="white")+
  geom_errorbar(aes(ymin = mm - 1.96*se, ymax=mm + 1.96*se), 
                position=position_dodge(.9), width=.2, size=1, alpha=1)+
  geom_signif(comparisons = list(c("No training", "Training")), annotation=c("**"),size=1.5,y_position=0.75,textsize=10)+
  labs(title="Study 1")+
  xlab("")+
  ylab("\nAccuracy")+
  ylim(0, 0.95)+
  theme_bw()+
  scale_color_manual(name = "", values = c("#EE0000FF", "#3B499299")) +
  scale_fill_manual(name = "", values = c("#EE0000FF", "#3B499299"))+
  guides(fill = guide_legend(reverse = TRUE))+
  guides(color = guide_legend(reverse = TRUE))+ 
  theme_ipsum_rc(grid="Y",axis_title_just="m")+
  theme(text=element_text(size=26),legend.position="no",aspect.ratio=1/1,plot.title = element_text(size=28,hjust = 0.5),
        axis.text.y = element_text(size=22,colour = "black"),axis.title.y = element_text(size=26),
        axis.text.x = element_text(size=24,colour="black"),
        legend.text=element_text(size=16),strip.background = element_rect(color="black",fill="white"),
        panel.border = element_rect(colour = "black", fill=NA, size=1.5), plot.margin = unit(c(0.1, 0, 0, 0), "cm"))

print(plt)

dev.off()

# END